package sskj.regulatory.arch;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qmui.arch.QMUIFragment;

public abstract class BaseMVPFragment<V extends BaseMVPContract.View, P extends BaseMVPContract.Presenter<V>>
        extends QMUIFragment implements BaseMVPContract.View {

    protected P presenter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        BaseViewModel<V, P> viewModel = ViewModelProviders.of( this ).get( BaseViewModel.class );
        boolean isPresenterCreated = false;
        if (viewModel.getPresenter() == null) {
            viewModel.setPresenter( initPresenter() );
            isPresenterCreated = true;
        }
        presenter = viewModel.getPresenter();
        presenter.attachLifecycle( getLifecycle() );

        presenter.attachView( (V) this );
        if (isPresenterCreated)
            presenter.onPresenterCreate();

        return super.onCreateView( inflater, container, savedInstanceState );
    }


    @CallSuper
    @Override
    public void onDestroyView() {
        presenter.detachLifecycle( getLifecycle() );
        presenter.detachView();
        super.onDestroyView();
    }

    protected abstract P initPresenter();
}
